package com.csu.analysis.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.csu.analysis.service.GpsService;
import com.csu.device.dao.HardWareDao;
import com.csu.device.entity.Behavior;
import com.csu.device.entity.Device;
import com.csu.device.service.HardWareService;
import com.csu.push.WebSocketPush;
import com.csu.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GpsServiceImpl implements GpsService {

    @Autowired
    private HardWareDao hardWareDao;

    @Autowired
    private HardWareService hardWareService;

    @Override
    public void gps(JSONObject jsonObject) {
        String deviceSn = jsonObject.getString("Serial");
        if(null==deviceSn)return;
        if (!RedisUtil.hasKey(deviceSn)) return;

        //获取gps数据
        Device gps = (Device) RedisUtil.get(deviceSn);
        JSONObject resJson = this.prssonGps(jsonObject);
        gps.setJsonObject(resJson);
        RedisUtil.set(deviceSn,gps);

        //推送gps
        WebSocketPush.gspPush(resJson, gps.getDeviceRelas());
    }


    /**
     * 查询所有gps信息
     * @return
     */
    @Override
    public List<Map<String, Object>> findGpsAll() {
        List<Map<String, Object>> mapList=new ArrayList<>();
        List<String> gpsList=hardWareDao.findAllGps();
        Map<String, Object> map;
        Behavior behavior;
        for(String gps:gpsList){
            Device device = (Device) RedisUtil.get(gps);
            if(null==device) continue;
            map=new HashMap<>();
            behavior=hardWareService.getDevRelaToDo(device.getDeviceRelas(),gps);
            map.put("userId",behavior.getFamilyUserId());
            map.put("userName",behavior.getFamilyUserName());
            map.put("json",device.getJsonObject());
            mapList.add(map);
        }

        return mapList;
    }


    /**
     * 解析gps数据
     * @param jsonObject
     * @return
     */
    private JSONObject prssonGps(JSONObject jsonObject) {
        //包含Longitude和Latitude
        JSONObject resJson = jsonObject.getJSONObject("Detail");
        JSONObject res = new JSONObject();

        //维度
        res.put("lt", resJson.getString("Longitude"));
        //经度
        res.put("la", resJson.getString("Latitude"));

        return res;

    }
}
